package com.chen.hotel.interceptor;

import com.chen.hotel.Service.UserService;
import com.chen.hotel.annotation.LoginToken;
import com.chen.hotel.annotation.PassToken;
import com.chen.hotel.domain.Users;
import com.chen.hotel.exception.HotelException;
import com.chen.hotel.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.lang.reflect.Method;

@Slf4j
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 检查是否添加了passToken注释，有则跳过认证
        if(method.isAnnotationPresent(PassToken.class)){
            PassToken passToken = method.getAnnotation(PassToken.class);
            if(passToken.required()){
                return true;
            }
        }
        // 检查是否有LoginToken注解，有则需要进行认证
        if(method.isAnnotationPresent(LoginToken.class)){
            String[] tokenArr = request.getHeader("authorization").split(" ");
            if(tokenArr.length < 2){
                throw new HotelException(403, "无效的token值");
            }
            String token = tokenArr[1];
            LoginToken loginToken = method.getAnnotation(LoginToken.class);
            if(loginToken.required()){
                if(StringUtils.isEmpty(token)){
                    throw new HotelException(403, "token值无效，请先登录");
                }
                Integer userId = TokenUtil.getUserId(token);
                if(userId == null){
                    throw new HotelException(403, "无效的token值，请登录");
                }
                Users users = this.userService.findById(userId);
                if(users == null){
                    throw new HotelException(403, "用户不存在");
                }
                if(TokenUtil.verify(token, users.getPassword())){
                    if(loginToken.auth().getCode() <= users.getAuth()){
                        request.setAttribute("userid", users.getId());
                        return true;
                    }else{
                        throw new HotelException(403, "您没有相应的权限执行此次操作");
                    }
                }else{
                    throw new HotelException(403, "无效的token值");
                }
            }
        }
        return true;
    }
}
